#include "CircularBufferDB/CircularBufferDB.h"
#include <iostream>
#include <cstring>
#include <chrono>
#include <thread>

// 示例记录类型1：基础事件记录
struct BasicEvent {
    time_t timestamp;
    char type[32];
    char message[256];
};

// 示例记录类型2：系统指标记录
struct SystemMetrics {
    time_t timestamp;
    double cpu_usage;
    double memory_usage;
    uint32_t process_count;
};

std::string MyRecordToString(const BasicEvent& record)
{
    return " Value: " + std::string(record.type) + " \tMessage: " + std::string(record.message) ;
}

int main() {
    try {
        // 初始化数据库（存储BasicEvent类型，容量5000条）
        CircularBufferDB<BasicEvent> event_db("events.db", 100000);

        // 写入示例数据
        for(int i = 0; i < 100; ++i){
            BasicEvent event{};
            strncpy(event.type, "INFO", sizeof(event.type));
            char message[256];
            sprintf(message, "This is event %d", i);
            strncpy(event.message, message, sizeof(event.message));
            event_db.AddRecord(event);
            // std::this_thread::sleep_for(std::chrono::milliseconds(100)); // 等待100毫秒
        }

        // 读取数据
        auto records = event_db.ReadRecords();
        for (const auto& r : records) {
            std::cout << "[" << ctime(&r.timestamp) 
                      << "] " << r.type << ": " << r.message << "\n";
        }

        // 测试 GetRecordsByTime 函数
        auto now = std::chrono::system_clock::now();
        auto start = now - std::chrono::seconds(10); // 10秒前
        auto end = now; // 当前时间

        // 将时间点转换为 time_t 类型并存储在变量中
        time_t start_time = std::chrono::system_clock::to_time_t(start);
        time_t end_time = std::chrono::system_clock::to_time_t(end);

        auto filtered_records = event_db.GetRecordsByTime(start, end);
        std::cout << "\nFiltered records between " << ctime(&start_time)
                  << " and " << ctime(&end_time) << ":\n";
        for (const auto& r : filtered_records) {
            std::cout << "[" << ctime(&r.timestamp) 
                      << "] " << r.type << ": " << r.message << "\n";
        }
        event_db.ExportToTextFile("exported_records.txt",MyRecordToString);

    } catch (const std::exception& e) {
        std::cerr << "Error: " << e.what() << std::endl;
        return 1;
    }
    return 0;
}